package org.dousb.doupicture.domain.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dousb.doupicture.application.service.SpaceApplicationService;
import org.dousb.doupicture.application.service.UserApplicationService;
import org.dousb.doupicture.domain.user.entity.Space;
import org.dousb.doupicture.domain.user.entity.SpaceUser;
import org.dousb.doupicture.domain.user.entity.User;
import org.dousb.doupicture.domain.user.service.SpaceUserDomainService;
import org.dousb.doupicture.domain.user.valueobject.SpaceRoleEnum;
import org.dousb.doupicture.infrastructure.common.ErrorCode;
import org.dousb.doupicture.infrastructure.exception.BusinessException;
import org.dousb.doupicture.infrastructure.exception.ThrowUtils;
import org.dousb.doupicture.infrastructure.mapper.SpaceUserMapper;
import org.dousb.doupicture.interfaces.dto.space_user.SpaceUserAddRequest;
import org.dousb.doupicture.interfaces.dto.space_user.SpaceUserQueryRequest;
import org.dousb.doupicture.interfaces.vo.space.SpaceUserVO;
import org.dousb.doupicture.interfaces.vo.space.SpaceVO;
import org.dousb.doupicture.interfaces.vo.user.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【space_user(空间用户关联)】的数据库操作Service实现
 * @createDate 2025-10-22 15:01:53
 */
@Service
public class SpaceUserDomainServiceImpl extends ServiceImpl<SpaceUserMapper, SpaceUser>
        implements SpaceUserDomainService {


    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    @Lazy
    private SpaceApplicationService spaceApplicationService;


    /**
     * 添加空间用户
     *
     * @param spaceUserAddRequest
     * @return
     */
    @Override
    public long addSpaceUser(SpaceUserAddRequest spaceUserAddRequest) {
        ThrowUtils.throwIf(spaceUserAddRequest == null, ErrorCode.PARAMS_ERROR);
        SpaceUser spaceUser = new SpaceUser();
        BeanUtils.copyProperties(spaceUserAddRequest, spaceUser);
        validSpaceUser(spaceUser, true);
        //添加
        boolean result = this.save(spaceUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "添加失败");
        return spaceUser.getId();
    }

    /**
     * 封装查询
     *
     * @param spaceUserQueryRequest
     * @param request
     * @return
     */
    @Override
    public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryRequest spaceUserQueryRequest, HttpServletRequest request) {
        QueryWrapper<SpaceUser> queryWrapper = new QueryWrapper<>();
        if (spaceUserQueryRequest == null) {
            return queryWrapper;
        }
        Long id = spaceUserQueryRequest.getId();
        Long spaceId = spaceUserQueryRequest.getSpaceId();
        Long userId = spaceUserQueryRequest.getUserId();
        String spaceRole = spaceUserQueryRequest.getSpaceRole();
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceRole), "spaceRole", spaceRole);
        return queryWrapper;
    }

    /**
     * 封装返回值
     *
     * @param spaceUser
     * @param request
     * @return
     */
    @Override
    public SpaceUserVO getSpaceUserVO(SpaceUser spaceUser, HttpServletRequest request) {
        SpaceUserVO spaceUserVO = SpaceUserVO.objToVo(spaceUser);
        Long userId = spaceUser.getUserId();
        //关联查询用户信息
        if (userId != null && userId > 0) {
            User user = userApplicationService.getUserById(userId);
            if (user != null) {
                UserVO UserVO = new UserVO();
                BeanUtils.copyProperties(user, UserVO);
                spaceUserVO.setUserVO(UserVO);
            }
        }
        //关联查询空间信息
        Long spaceId = spaceUser.getSpaceId();
        if (spaceId != null && spaceId > 0) {
            Space space = spaceApplicationService.getById(spaceId);
            SpaceVO spaceVO = SpaceVO.objToVo(space);
            spaceUserVO.setSpaceVO(spaceVO);
        }
        return spaceUserVO;
    }

    /**
     * 批量封装返回值
     *
     * @param spaceUserList
     * @param request
     * @return
     */
    @Override
    public List<SpaceUserVO> getSpaceUserVOList(List<SpaceUser> spaceUserList, HttpServletRequest request) {
        //判断列表是否为空
        if (CollUtil.isEmpty(spaceUserList)) {
            return new ArrayList<>();
        }
        //对象列表-》封装对象
        List<SpaceUserVO> spaceUserVOList = spaceUserList.stream()
                .map(SpaceUserVO::objToVo)
                .collect(Collectors.toList());
        //收集需要关联查询的用户id和空间id
        Set<Long> userIdsSet = spaceUserVOList.stream()
                .map(SpaceUserVO::getUserId)
                .collect(Collectors.toSet());
        Set<Long> spaceIdsSet = spaceUserVOList.stream()
                .map(SpaceUserVO::getSpaceId)
                .collect(Collectors.toSet());
        //批量查询用户和空间
        Map<Long, List<User>> userIdUserListMap = userApplicationService.listByIds(userIdsSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        Map<Long, List<Space>> spaceIdSpaceListMap = spaceApplicationService.listByIds(spaceIdsSet).stream()
                .collect(Collectors.groupingBy(Space::getId));
        //填充用户和空间信息
        spaceUserVOList.forEach(spaceUserVO -> {
            Long userId = spaceUserVO.getUserId();
            Long spaceId = spaceUserVO.getSpaceId();
            //填充用户信息
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceUserVO.setUserVO(userApplicationService.getUserVO(user));
            //填充空间信息
            Space space = null;
            if (spaceIdSpaceListMap.containsKey(spaceId)) {
                space = spaceIdSpaceListMap.get(spaceId).get(0);
            }
            spaceUserVO.setSpaceVO(SpaceVO.objToVo(space));
        });
        return spaceUserVOList;
    }

    /**
     * 校验空间用户
     *
     * @param spaceUser
     */
    @Override
    public void validSpaceUser(SpaceUser spaceUser, boolean add) {
        ThrowUtils.throwIf(spaceUser == null, ErrorCode.PARAMS_ERROR);
        Long spaceId = spaceUser.getSpaceId();
        Long userId = spaceUser.getUserId();
        //校验
        if (add) {
            ThrowUtils.throwIf(ObjUtil.hasEmpty(spaceId, userId), ErrorCode.PARAMS_ERROR);
            User user = userApplicationService.getUserById(userId);
            ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR, "用户不存在");
            Space space = spaceApplicationService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR, "空间不存在");
        }
        //校验空间角色
        String spaceRole = spaceUser.getSpaceRole();
        SpaceRoleEnum spaceRoleEnum = SpaceRoleEnum.getEnumByValue(spaceRole);
        if (spaceRoleEnum == null && spaceRole != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间角色不存在");
        }
        //校验是否已经加入空间
        LambdaQueryWrapper<SpaceUser> spaceUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spaceUserLambdaQueryWrapper.eq(SpaceUser::getId, spaceId)
                .eq(SpaceUser::getUserId, userId);
        SpaceUser spaceUserExist = this.getOne(spaceUserLambdaQueryWrapper);
        ThrowUtils.throwIf(spaceUserExist != null, ErrorCode.PARAMS_ERROR, "用户已加入空间");
    }

    /**
     * 校验图片空间的权限
     *
     * @param loginUser
     * @param spaceUser
     */
//    @Override
//    public void checkSpaceUserAuth(User loginUser, SpaceUser spaceUser) {
//        Long spaceId = spaceUser.getSpaceId();
//        if (spaceId == null) {
//            //公共空间 空间创建者 和 管理员
//            if (!spaceUser.getUserId().equals(loginUser.getId()) && !loginUser.isAdmin()) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作");
//            }
//        } else {
//            //私有空间 仅空间创建者可以
//            if (!spaceUser.getUserId().equals(loginUser.getId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作");
//            }
//        }
//    }
}




